<?php

namespace addons\qingdongams\controller;

use addons\qingdongams\library\ReceiveMail;
use think\Request;
/**
 * 邮箱管理
 */
class Receiveemail extends StaffApi {
	protected $noNeedLogin = [];
	protected $noNeedRight = [];
    protected $formater = ['gif','jpeg','png','jpg','bmp'];
    public $mailAccount;
    public $mailPasswd;
    public $mailAddress;
    public $mailServer = "pophz.qiye.163.com";
    public $serverType = "pop3";
    public $port = "110";
    public $now       = 0;
    public $savePath;
    public $webPath   = "../upload/";

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->mailAccount=$this->auth->email;
        $this->mailPasswd=$this->auth->email_code;
        $this->mailAddress=$this->auth->email;
        $this->savePath = ROOT_PATH;

    }

    // 收件箱列表
    public function getEmails()
    {
        $limit = input("limit/d", 10);
        $isRead = input("is_read",'');
        $theme = input("name",'');
        if(isset($isRead) && is_numeric($isRead) && in_array($isRead,[0,1])){
            $where['is_read'] = $isRead;
        }
        if($theme){
            $where['theme'] = ['like','%'.$this.'%'];
        }
        $where['staff_id'] = $this->auth->id;
        $email = new \addons\qingdongams\model\ReceiveEmail();
        $list = $email->where($where)->field('createtime,updatetime',true)->field('content',true)->paginate($limit);
        $this->success('',$list);
    }

    // 获取详情
    public function detailEmail(){
        $id = input('id');
        $email = new \addons\qingdongams\model\ReceiveEmail();
        $email->isUpdate(true)->save(['is_read'=>1],['id'=>$id]);
        $detail = $email->with('staff')->where(['id'=>$id,'staff_id'=>$this->auth->id])->find();
        $this->success('',$detail);
    }

    // 删除邮件
    public function delEmail(){
        $id = input('id');
        $email = new \addons\qingdongams\model\ReceiveEmail();
        $res = $email->where('id',$id)->find();
        if(!$res){
            $this->error('邮件不存在');
        }
        if($email->destroy($id) !== false){
            $this->success('删除成功');
        }
        $this->error('稍后再试');

    }

    // 下载附件
    public function downloadFile(){
        $id = input('id');
        $email = new \addons\qingdongams\model\ReceiveEmail();
        $fileIds = $email->where('id',$id)->value('attach');
        if(!$fileIds){
            $this->error('无附件可下载');
        }
        $filePaths = \addons\qingdongams\model\File::where('id','in',explode(',',$fileIds))->column('file_path');
        foreach ($filePaths as $v){
            $file = ROOT_PATH.'public'.$v;
            download($file);
        }

    }


    /**
     * 无用，前期测试用到
     * mail Received()读取收件箱邮件
     *
     * @param
     * @access public
     * @return result
     */
    public function mailReceived()
    {
        // Creating a object of reciveMail Class
        $obj= new  ReceiveMail($this->mailAccount,$this->mailPasswd,$this->mailAddress,$this->mailServer,$this->serverType,$this->port,false);
        //Connect to the Mail Box
        $res=$obj->connect();         //If connection fails give error message and exit
        if (!$res)
        {
            return array("msg"=>"Error: Connecting to mail server");
        }
        // Get Total Number of Unread Email in mail box
        $tot=$obj->getTotalMails(); //Total Mails in Inbox Return integer value
        if($tot < 1) { //如果信件数为0,显示信息
            return array("msg"=>"No Message for ".$this->mailAccount);
        }
        else
        {
            $res=array("msg"=>"Total Mails:: $tot<br>");

            for($i=$tot;$i>0;$i--)
            {
                $head=$obj->getHeaders($i);  // Get Header Info Return Array Of Headers **Array Keys are (subject,to,toOth,toNameOth,from,fromName)

                //处理邮件附件
                $files=$obj->GetAttach($i,$this->savePath); // 获取邮件附件，返回的邮件附件信息数组
                $imageList=array();
                foreach($files as $k => $file)
                {
                    //type=1为附件,0为邮件内容图片
                    if($file['type'] == 0)
                    {
                        $imageList[$file['title']]=$file['pathname'];
                    }
                }
                $body = $obj->getBody($i,$this->webPath,$imageList);
                $res['mail'][]=array('head'=>$head,'body'=>$body,"attachList"=>$files);
            }
            $obj->close_mailbox();   //Close Mail Box
            return $res;
        }
    }



}
